#include "h_spi_s.h"

// typedef struct
// {
//     void (*sck_out_init)(void);
//     void (*sck_high)(void);
//     void (*sck_low)(void);
//     void (*cs_out_init)(void);
//     void (*cs_high)(void);
//     void (*cs_low)(void);
//     void (*mosi_out_init)(void);
//     void (*mosi_high)(void);
//     void (*mosi_low)(void);
//     void (*miso_in_init)(void);
//     signed char (*miso_read)(void);
//     void (*delay_us)(unsigned int);
// }h_spi_s_t;

void h_spi_s_init(h_spi_s_t *spi)
{
    spi->sck_out_init();
    spi->cs_out_init();
    spi->mosi_out_init();
    spi->miso_in_init();

    spi->sck_low();
    spi->cs_high();
    spi->mosi_low();

}

void h_spi_s_read_buffer(h_spi_s_t *spi, unsigned char *data, unsigned short len)
{
    unsigned char i;
    unsigned char tdata;
    while(len--)
    {
        tdata = 0;
        for(i = 0U; i < 8; i++)
        {
            tdata <<= 1;
            spi->sck_high();
            if(spi->miso_read())
            {
                tdata |= 0x01;
            }
            spi->sck_low();
        }
        *data++ = tdata;
    }
}

void h_spi_s_write_buffer(h_spi_s_t *spi, unsigned char *data, unsigned short len)
{
    unsigned char i;
    unsigned char tdata;

    while(len--)
    {
        tdata = *data++;
        for(i = 0U; i < 8; i++)
        {
            spi->sck_low();
            if(tdata & 0x80)
            {
                spi->mosi_high();
            }
            else
            {
                spi->mosi_low();
            }
            spi->sck_high();
            tdata <<= 1;
        }

        spi->sck_low();
        spi->mosi_low();
    }
}